#include "lwip/tcp.h"
#include "lwip/priv/tcp_priv.h"

static inline bool tcp_skb_sent_after(u64_t t1, u64_t t2, u32_t seq1, u32_t seq2)
{
	return t1 > t2 || (t1 == t2 && TCP_SEQ_GT(seq1, seq2));
}

/* Snapshot the current delivery information in the skb, to generate
 * a rate sample later when the skb is (s)acked in tcp_rate_skb_delivered().
 */
void tcp_rate_skb_sent(struct tcp_pcb *tp, struct tcp_seg *skb)
{
	 /* In general we need to start delivery rate samples from the
	  * time we received the most recent ACK, to ensure we include
	  * the full time the network needs to deliver all in-flight
	  * packets. If there are no packets in flight yet, then we
	  * know that any ACKs after now indicate that the network was
	  * able to deliver those packets completely in the sampling
	  * interval between now and the next ACK.
	  *
	  * Note that we use packets_out instead of tcp_packets_in_flight(tp)
	  * because the latter is a guess based on RTO and loss-marking
	  * heuristics. We don't want spurious RTOs or loss markings to cause
	  * a spuriously small time interval, causing a spuriously high
	  * bandwidth estimate.
	  */
	if (!tcp_packets_in_flight(tp)) {
		u64_t tstamp_us = skb->skb_mstamp_us;

		tp->first_tx_mstamp  = tstamp_us;
		tp->delivered_mstamp = tstamp_us;
	}

	skb->tx.first_tx_mstamp	= tp->first_tx_mstamp;
	skb->tx.delivered_mstamp	= tp->delivered_mstamp;
	skb->tx.delivered		= tp->delivered;
	skb->tx.is_app_limited	= tp->app_limited ? 1 : 0;
    LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_rate_skb_sent(): tcp_packets_in_flight %u skb_mstamp_us %lu\n", tcp_packets_in_flight(tp), skb->skb_mstamp_us));
}

/* When an skb is sacked or acked, we fill in the rate sample with the (prior)
 * delivery information when the skb was last transmitted.
 *
 * If an ACK (s)acks multiple skbs (e.g., stretched-acks), this function is
 * called multiple times. We favor the information from the most recently
 * sent skb, i.e., the skb with the most recently sent time and the highest
 * sequence.
 */
void tcp_rate_skb_delivered(struct tcp_pcb *tp, struct tcp_seg *scb,
			    struct rate_sample *rs)
{
	u64_t tx_tstamp;

	if (!scb->tx.delivered_mstamp)
		return;

	tx_tstamp = scb->skb_mstamp_us;
    if (!rs->prior_delivered || tcp_skb_sent_after(tx_tstamp, tp->first_tx_mstamp, scb->end_seq, rs->last_end_seq))
    {
        rs->prior_delivered  = scb->tx.delivered;
		rs->prior_mstamp     = scb->tx.delivered_mstamp;
		rs->is_app_limited   = scb->tx.is_app_limited;
		rs->is_retrans	     = scb->flags & TF_SEG_RETRANS;
        rs->last_end_seq     = scb->end_seq;

        /* Record send time of most recently ACKed packet: */
		tp->first_tx_mstamp  = tx_tstamp;
		/* Find the duration of the "send phase" of this window: */
		rs->interval_us = tcp_stamp_us_delta(tp->first_tx_mstamp,
						     scb->tx.first_tx_mstamp);
        LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_rate_skb_delivered(): update rs scb->end_seq %u skb_mstamp_us %lu\n", scb->end_seq, tx_tstamp));
    }
}

/* Update the connection delivery information and generate a rate sample. */
void tcp_rate_gen(struct tcp_pcb *tp, u32_t delivered,struct rate_sample *rs)
{
	u32_t snd_us, ack_us;

	/* Clear app limited if bubble is acked and gone. */
	if (tp->app_limited && TCP_SEQ_GT(tp->delivered,tp->app_limited))
		tp->app_limited = 0;
        
	/* TODO: there are multiple places throughout tcp_ack() to get
	 * current time. Refactor the code using a new "tcp_acktag_state"
	 * to carry current time, flags, stats like "tcp_sacktag_state".
	 */
	if (delivered)
		tp->delivered_mstamp = tp->tcp_mstamp;

	rs->acked_sacked = delivered;	/* freshly ACKed or SACKed */
	rs->losses = 0;		/* freshly marked lost */
	/* Return an invalid sample if no timing information is available or
	 * in recovery from loss with SACK reneging. Rate samples taken during
	 * a SACK reneging event may overestimate bw by including packets that
	 * were SACKed before the reneg.
	 */
	if (!rs->prior_mstamp) {
		rs->delivered = -1;
		rs->interval_us = -1;
		return;
	}
	rs->delivered   = tp->delivered - rs->prior_delivered;

	/* Model sending data and receiving ACKs as separate pipeline phases
	 * for a window. Usually the ACK phase is longer, but with ACK
	 * compression the send phase can be longer. To be safe we use the
	 * longer phase.
	 */
	snd_us = rs->interval_us;				/* send phase */
	ack_us = tcp_stamp_us_delta(tp->tcp_mstamp,
				    rs->prior_mstamp); /* ack phase */
	rs->interval_us = LWIP_MAX(snd_us, ack_us);

	/* Record both segment send and ack receive intervals */
	rs->snd_interval_us = snd_us;
	rs->rcv_interval_us = ack_us;

	/* Normally we expect interval_us >= min-rtt.
	 * Note that rate may still be over-estimated when a spuriously
	 * retransmistted skb was first (s)acked because "interval_us"
	 * is under-estimated (up to an RTT). However continuously
	 * measuring the delivery rate during loss recovery is crucial
	 * for connections suffer heavy or prolonged losses.
	 */
	if (unlikely(rs->interval_us < 300)) {
		rs->interval_us = -1;
		return;
	}

    	/* Record the last non-app-limited or the highest app-limited bw */
	if (!rs->is_app_limited ||
	    ((u64_t)rs->delivered * tp->rate_interval_us >=
	     (u64_t)tp->rate_delivered * rs->interval_us)) {
		tp->rate_delivered = rs->delivered;
		tp->rate_interval_us = rs->interval_us;
		tp->rate_app_limited = rs->is_app_limited;
	}

    LWIP_DEBUGF(TCP_CWND_DEBUG,("tcp_rate_gen(): rs->interval_us %ld rs->delivered %d rs->prior_delivered %u\n",rs->interval_us,rs->delivered,rs->prior_delivered));
}

/* If a gap is detected between sends, mark the socket application-limited. */
void tcp_rate_check_app_limited(struct tcp_pcb *tp)
{
	LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_rate_check_app_limited(): snd_lbb-snd_nxt=%u queuelen=%d\n", tp->snd_lbb - tp->snd_nxt, tp->snd_queuelen));
	if (/* We have less than one packet to send. */
	    tp->snd_lbb - tp->snd_nxt < tp->mss &&
	    /* Nothing in sending host's qdisc queues or NIC tx queue. */
	    tp->snd_queuelen < 1 &&
	    /* We are not limited by CWND. */
	    tcp_packets_in_flight(tp) < tp->cwnd) {
		tp->app_limited =
			(tp->delivered + tcp_packets_in_flight(tp)) ? : 1;
        LWIP_DEBUGF(TCP_CWND_DEBUG,("tcp_rate_check_app_limited(): condition ok! app_limited %u\n",tp->app_limited));
        }
}
